//index.js
const pageUtil = require('../../utils/page.js');
const util = require('../../utils/util.js');
const pay = require('../../utils/pay.js');
const app = getApp();

function getAccount(callback) {
  wx.request({
    url: app.processUri('accounts/_'),
    method: "GET",
    header: { 'Authorization': app.globalData.accessToken },
    success: function (res) {
      callback(res.data);
    },
  });
}

function fetchPost(postId, callback) {
  let post = app.postCache.restore(postId);
  if (post == null) {
    wx.request({
      url: app.processUri('posts', postId),
      method: "GET",
      success: function (res) {
        app.postCache.persist(res.data);
        callback(res.data);
      }
    });
  } else callback(post);
}


Page({
  postId: 0,
  post: '',
  data: {
    currentDate: util.formatDate(new Date(), false, true),
    contentFontSize: 120,
    customDateLabel: '',
    editing: false,
    recording: false,
    recordCancelling: false,
    previewMode: false,
    recordingSeconds: 0,
    cardImage: '',
    avatarImage: '',
    festivalNames: [],
    festivalIndex: 0,

    isMe: false,
    showPayPanel: false,
    nickName: '',
    fontSize: 120,
  },

  logining: false,
  committed: false,
  festivals: [],
  resources: null,
  fetchFestivalTime: 0,

  onLoad: function (options) {
    this.tipsAnimation = wx.createAnimation({
      duration: 500,
      delay: 400
    });
    this.cardAnimation = wx.createAnimation({ duration: 200 });
    this.userAnimation = wx.createAnimation({ duration: 500 });
    this.buttonAnimation = wx.createAnimation({ duration: 500 });

    this.postId = parseInt(options.postId);
    console.log(this.postId)
  },

  onReady: function () {
    const page = this;
    this.startLogin();
    app.changeStyle(this);
    // this.resetPage();
    // fetchPost(page.postId, (data) => {
    //   console.log(data.account.id)
    //   console.log(app.globalData.accountId)
    //   page.setData({
    //     avatarImage: data.account.avatar,
    //     nickName: data.account.name,
    //     isMe: data.account.id == app.globalData.accountId,
    //   });
    // });
  },

  startLogin: function () {
    const page = this;
    pageUtil.startLoading(page);
    page.logining = true;
    app.loadUserInfo((info) => {
      if (info != null) {
        page.setData({ avatarImage: info.avatarUrl });
        app.refreshAccessToken(() => {
          page.logining = false;
          pageUtil.stopLoading(page);
          page.refreshDate(page.fetchFestivalTime == 0);
        });
      } else {
        wx.showModal({
          title: '错误',
          content: '无法获取用户信息，点击重试',
          showCancel: false,
          complete: () => {
            page.startLogin();
          }
        });
      }
    });
  },

  onShow: function () {
    const page = this;
    if (util.currentTime() - page.fetchFestivalTime > 60000) page.refreshDate();
    getAccount((account) => {
      page.accountUpdateTime = account.modifyTime;
      page.setData({ hasAccountChange: page.accountUpdateTime > app.globalData.accountUpdateTime });
    });
  },

  onHide: function () {
    wx.stopVoice();
    if (this.committed) {
      this.committed = false;
      this.resetPage()
    }
  },
  showPayPanel: function () {
    const page = this;
    page.payMount = Math.ceil(Math.random() * 500);
    page.setData({
      showPayPanel: true,
      payValue: util.formatChineseCurrency(page.payMount)
    });
  },
  hidePayPanel: function () {
    this.setData({ showPayPanel: false });
  },
  openAssessPage: function () {
    wx.navigateTo({ url: '../../pages/assess/assess' });

  },
  refreshDate: function (forceData) {
    const page = this;
    const newDate = util.formatDate(new Date(), false, true);
    if (page.data.currentDate != newDate) {
      page.setData({ currentDate: newDate });
      page.fetchFestivals();
    } else if (forceData == true) {
      page.fetchFestivals();
    }
  },
  fetchFestivals: function () {
    const page = this;
    page.fetchFestivalTime = 0;
    if (app.globalData.accessToken == null || app.globalData.accessToken == '') {
      return;
    }
    const requestToken = app.globalData.accessToken;
    pageUtil.startLoading(page);
    wx.request({
      url: app.processUri('festivals?millis=' + (new Date()).getTime()),
      method: "GET",
      header: { 'Authorization': requestToken },
      success: (res) => {
        page.fetchFestivalTime = util.currentTime();
        if (res.statusCode == 401) {
          if (page.logining) {
            page.fetchFestivalTime = 0;
          } else if (requestToken != app.globalData.accessToken) page.fetchFestivals();
        } else if (res.data.length > 0) {
          page.festivals = res.data;
          const festivalNames = [];
          page.festivals.forEach(res => {
            let name = res['name'];
            if (name == null || name == '') name = util.formatChineseDate(res.month, res.day);
            res['name'] = name;
            festivalNames.push(name);
          });
          page.setData({
            festivalNames: festivalNames,
            festivalIndex: 0
          });
          page.setFestival(page.festivals[0]);
        }
      },
      complete: () => { pageUtil.stopLoading(page) }
    })
  },

  inputingText: function (res) {
    let text = res.detail.value;
    const textLength = util.chineseStringLength(text);
    if (textLength > app.globalData.maxLabelSize) {
      text = text.substring(0, util.chineseStringLengthIndex(text, app.globalData.maxLabelSize));
    }
    this.refreshLabelTextSize(text);
    return text;
  },

  refreshLabelTextSize: function (text) {
    const newSize = util.computeFontSize(text);
    if (newSize != this.data.contentFontSize) {
      this.setData({
        contentFontSize: newSize
      });
    }
  },

  initFestivalResourceGroup: function () {
    const list = this.resources
      .filter(value => { return value.type == 0 })
      .map(value => {
        return {
          id: value['id'],
          name: value['name'],
          preview: app.processUri(value['preview']),
          param: JSON.parse(value['param']),
          uri: value['uri']
        }
      });
    this.setData({ cardResourceGroups: util.groupArray(list, 5) });
    if (list.length > 0) {
      this.switchToCardResource(list[0]);
    }
  },

  startEditing: function () {
    this.setData({ editing: true })
  },
  endMoneyEditing: function () {
    const page = this;
    page.setData({
      moneyEditing: false,
      payValue: util.formatChineseCurrency(page.payMount)
    });
  },
  inputingMoney: function (res) {
    const text = res.detail.value;
    const value = parseFloat(text);
    if (isNaN(value) || value < 0) return 0.01; else {
      this.payMount = parseInt(value * 100);
      return text;
    }
  },
  startOrCancelMoneyEditing: function () {
    if (this.data.moneyEditing) {
      this.payMount = parseInt(parseFloat(this.data.payValue) * 100);
      this.setData({ moneyEditing: false, });
    } else this.startMoneyEditing();
  },
  startMoneyEditing: function () {
    this.setData({ moneyEditing: true });
  },
  endMoneyEditing: function () {
    const page = this;
    page.setData({
      moneyEditing: false,
      payValue: util.formatChineseCurrency(page.payMount)
    });
  },
  doPay: function () {
    const page = this;
    wx.request({
      url: app.processUri('accounts/_/payments'),
      method: "POST",
      data: { paymentAccountId: page.post.account.id, paymentPostId: page.postId, value: page.payMount, summary: page['paySummary'] },
      header: { 'Authorization': app.globalData.accessToken },
      success: (res) => {
        if (app.globalData.userInfo == null) {
          // 没有用户信息，重新登录
          page.doLogin((success) => {
            if (success) {
              console.log('login finish.')
              page.doPay();
            }
          });
        } else {
          const payment = res.data;
          wx.showLoading({ title: '处理中...' });
          pay.startPayment(
            payment.prepayId,
            payment.timeStamp,
            payment.clientNonceStr,
            payment.clientSign,
            payment.clientSignType,
            (success) => {
              wx.hideLoading();
              if (success) {
                wx.request({
                  url: app.processUri('accounts/_/payments', payment.id, 'confirm'),
                  method: "POST",
                  header: { 'Authorization': app.globalData.accessToken },
                  complete: () => {
                    wx.navigateTo({
                      url: '/pages/detail/success/success?postId=' + page.postId + '&money=' + page.payMount
                      + '&summary=' + payment.summary
                      + '&time=' + new Date().getTime()
                    });
                  }
                });
              } else {
                wx.showToast({
                  title: '支付失败。'
                });
              }
            });
        }
      },
      complete: () => { page.hidePayPanel(); }
    });
  },
  endEditing: function (e) {
    this.setData({
      editing: false,
      customDateLabel: e.detail.value
    })
  },

  openWallet: function () {
    wx.navigateTo({ url: '../../pages/wallet/wallet' });
  }
})

// wx.showShareMenu({
//   withShareTicket: true
// })

